<?php
namespace Api\Controller;
use Think\Controller\RestController;
use Think\Upload;
class StaffController extends CommonController{
    
    // 员工、组长、质检员列表
    public function userlists()
    {
        $user = D("user");
        $post = I('post.');
        $types = $post["types"];
        $where['types'] = $types;
        $where['deletetime'] = array('eq', 0);
        $where = $this->_search('User');
        if ($post['keyword']) {
            $where['names'] = ['like', '%' . $post['keyword'] . '%'];
        }
        $uid =$this->kh_uid;
        if($uid) {
            $where['uid'] = $uid;
        }
        $count = $user->where($where)->count();
        $lists =
            $user
            ->where($where)
            ->page($post['page'])
            ->limit($post['limit'] ? $post['limit'] : 20)
            ->order("uid desc")
            ->select();
        foreach($lists as &$val){
            unset($val['password']);
        }
        $data['list'] = $lists;
        $data['count'] = $count;
        if ($lists) {
            $this->ajaxReturn(array('code' => 200, 'msg' => '查询成功', 'data' => $data), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 200, 'msg' => '查询成功', 'data' => $data), 'JSON');
        }
    }


    public function add(){
        $detail = I('post.');
        $staff = M("staff");
        $user = M("user");
        //检测是否有会员账号 没有则新增
        $stName = $detail["stName"];
        $stIszc =0;
        $username=$detail["username"];
        $password=$detail["password"];
        $stype=$detail["stype"]?:0;
        $sc = [];
        $sc['stName'] = $stName;
        $sc['deletetime'] = 0;
        $user_info = $staff->where($sc)->find();
        //检测会员账号是否已注册
        $guser=$user->where(['deletetime'=>0,'username'=>$username])->count();
        $stnoc=$this->getsn('YGBH');
        if($guser){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "登录账号已存在";
            exit(json_encode($data_cc));
        }
        $msdc=$this->validation_filter_id_card($detail["stSfz"]);
        if(empty($stName)){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "请输入姓名";
            exit(json_encode($data_cc));
        }
        if(empty($detail["stSfz"])){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "请输入身份证号";
            exit(json_encode($data_cc));
        }
        if($msdc==false){
            $data_cc['code'] = 0;
            $data_cc['msg'] ='身份证验证失败';
            exit(json_encode($data_cc));
        }
        if(!$this->checkMoty($detail["stMobile"])){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "手机号码格式不正确";
            exit(json_encode($data_cc));
        }
        if(empty($user_info['uid'])){
            $salt = $this->GetRandStr(6);
            $fdh = [];
            $fdh['types'] = 1;
            $fdh['isgl'] = 0;
            $fdh['password'] = $this->getEncryptPassword($password, $salt);
            $fdh['salt'] = $salt;
            $fdh['customer_no'] = $stnoc;
            $fdh['username'] = $detail["username"];
            $fdh['mobile'] = $detail["stMobile"];
            $fdh['names'] = $detail["stName"];
            $fdh['sex'] = $detail["stSex"];
            $fdh['status'] = 1;
            $fdh['addtime'] = date('Y-m-d H:i:s');
            $uid = $this->check_user($fdh);
            $data["uid"] =$uid;
        }
     
        $data["stNo"] =$stnoc;
        $data["stName"] = $detail["stName"];
        $data["stSfz"] = $detail["stSfz"];
        $data["stBirthdate"] = $detail["stBirthdate"];
        $data["stEntryDate"] = $detail["stEntryDate"];
        $data["stMobile"] = $detail["stMobile"];
        $data["stIszc"] =0;
        $data["isjb"] =0;
        $data["stSex"] = $detail["stSex"];
        if($stype==1){
            $data["hour_price"] = $detail["hour_price"];
            $data["stGid"] = $detail["stGid"];
            $data["stCid"] = 0;
        }else{
            $data["gxcate"] = $detail["gxcate"];
            $data["gx_cc"] = $detail["gx_cc"];
            $data["stCid"] = $detail["stCid"];
        }
        $result = $staff->add($data);
        if($result) {
            $data_cc['code'] = 200;
            $data_cc['msg'] = "添加成功";
            exit(json_encode($data_cc));
        } else {
            $data_cc['code'] = 200;
            $data_cc['msg'] = "添加失败";
            exit(json_encode($data_cc));
        }
    }

    //详情 
    public function detail(){
        $detail = I('post.');
        $staff = M("staff");
        $stId = $detail["stId"];
        $stype = $detail["stype"];
        $info=$staff->where(['stId'=>$stId])->find();
        if($info){
            $data_cc['code'] =200;
            $data_cc['msg'] = "查询成功";
            $data_cc['data']['info'] = $info;
            exit(json_encode($data_cc));
        }
    }
    //编辑
    public function edit(){
        $detail = I('post.');
        $stId = $detail["stId"];
        $stype = $detail["stype"];
        $stName = $detail["stName"];
        $staff = M("staff");
        if(empty($stName)){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "请输入姓名";
            exit(json_encode($data_cc));
        }
        if(empty($detail["stSfz"])){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "请输入身份证号";
            exit(json_encode($data_cc));
        }
        $msdc=$this->validation_filter_id_card($detail["stSfz"]);
        if($msdc==false){
            $data_cc['code'] = 0;
            $data_cc['msg'] ='身份证验证失败';
            exit(json_encode($data_cc));
        }
        if(!$this->checkMoty($detail["stMobile"])){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "手机号码格式不正确";
            exit(json_encode($data_cc));
        }
        //检测手机号是否存在了
        $dsa['stId']=['neq',$stId];
        $dsa['stMobile']=$detail["stMobile"];
        $cdstw=$staff->where($dsa)->count();
        if($cdstw){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "该手机号已经存在了";
            exit(json_encode($data_cc));
        } 
        $data["stName"] = $detail["stName"];
        $data["stSfz"] = $detail["stSfz"];
        $data["stBirthdate"] = $detail["stBirthdate"];
        $data["stEntryDate"] = $detail["stEntryDate"];
        $data["stMobile"] = $detail["stMobile"];
        $data["stIszc"] =0;
        $data["isjb"] =0;
        $data["stSex"] = $detail["stSex"];
        if($stype==1){
            $data["hour_price"] = $detail["hour_price"];
            $data["stGid"] = $detail["stGid"];
            $data["stCid"] = 0;
        }else{
            $data["gxcate"] = $detail["gxcate"];
            $data["gx_cc"] = $detail["gx_cc"];
            $data["stCid"] = $detail["stCid"];
        }
        $info=$staff->where(['stId'=>$stId])->find();
        if($info){
           $result=$staff->where(['stId'=>$stId])->save($data);
           if($result) {
                $data_cc['code'] = 200;
                $data_cc['msg'] = "编辑成功";
                exit(json_encode($data_cc));
            } else {
                $data_cc['code'] = 200;
                $data_cc['msg'] = "编辑失败";
                exit(json_encode($data_cc));
            }
        }else{

            $data_cc['code'] =0;
            $data_cc['msg'] = "信息查询失败";
            exit(json_encode($data_cc));
        }
    }

    function check_user($cdsy)
    {
        $user = M("user");
        $user_info = $user->where(['customer_no' => $cdsy['customer_no'], 'username' => $cdsy['username'], 'types' => 1])->find();
        if (empty($user_info)) {
            $user->add($cdsy);
            return $user->getLastInsID();
        } else {
            return $user_info['uid'];
        }
    }
    //员工编号字段生产
    function stnoc(){
        $staff = M("staff");
        $countc=$staff->where(['deletetime'=>0])->count();
        return 'Employee_No'.($countc+1);
    }

    // 手机号码验证
    function checkMoty($mobilephone){
        $exp = "/^13[0-9]{1}[0-9]{8}$|15[012356789]{1}[0-9]{8}$|18[012356789]{1}[0-9]{8}$|14[57]{1}[0-9]$/";
        if(preg_match($exp,$mobilephone)){
            return true;
        }else{
            return false;
        }
    }

    function validation_filter_id_card($id_card){
        if(strlen($id_card)==18){
            return $this->idcard_checksum18($id_card);
        }elseif((strlen($id_card)==15)){
            $id_card=$this->idcard_15to18($id_card);
            return $this->idcard_checksum18($id_card);
        }else{
            return false;
        }
    }
    // 计算身份证校验码，根据国家标准GB 11643-1999
    function idcard_verify_number($idcard_base){
        if(strlen($idcard_base)!=17){
            return false;
        }
        //加权因子
        $factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
        //校验码对应值
        $verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
        $checksum=0;
        for($i=0;$i<strlen($idcard_base);$i++){
            $checksum += substr($idcard_base,$i,1) * $factor[$i];
        }
        $mod=$checksum % 11;
        $verify_number=$verify_number_list[$mod];
        return $verify_number;
    }
    // 将15位身份证升级到18位
    function idcard_15to18($idcard){
        if(strlen($idcard)!=15){
            return false;
        }else{
            // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
            if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
                $idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
            }else{
                $idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
            }
        }
        $idcard=$idcard.$this->idcard_verify_number($idcard);
        return $idcard;
    }
    // 18位身份证校验码有效性检查
    function idcard_checksum18($idcard){
        if(strlen($idcard)!=18){
            return false;
        }
        $idcard_base=substr($idcard,0,17);
        if($this->idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
            return false;
        }else{
            return true;
        }
    }
    //编辑员工
    public function update()
    {
        $result = [
            'code' => 200,
            'data' => '',
            'msg' => '编辑成功'
        ];
        $stId = $_POST["stId"];
        $staff = M("staff");
        //查询组长是否存在
        if ($_POST["stZuzhang"]) {
            $rsc = $staff->where(['stNo' => $_POST['stZuzhang']])->find();
            if (empty($rsc)) {
                $result['code'] = 400;
                $result['msg'] = '队长编号不存在';
                $this->response($result, "json", 400);
            }
        }
        $data["stName"] = $_POST["stName"];
        $data["stNo"] = $_POST["stNo"];
        $data["stSfz"] = $_POST["stSfz"];
        $data["stMobile"] = $_POST["stMobile"];
        $data["stCid"] = $_POST["stCid"];
        $data["stZuzhang"] = $_POST["stZuzhang"];
        $data["stIszc"] = $_POST["stIszc"];
        $data["stIsjb"] = $_POST["stIsjb"];
        $data["isjb"] = $_POST["isjb"];
        $data["stSex"] = $_POST["stSex"];
        $data["stBirthdate"] = $_POST["stBirthdate"];
        $data["stEntryDate"] = $_POST["stEntryDate"];
        $data["stGid"] = $_POST["stGid"];
        $data["gxcate"] = $_POST["gxcate"];
        $data["gx_cc"] = $_POST["gx_cc"];
        $ret = $staff->where("stId=$stId")->save($data);
        if ($ret) {
            $result['data'] = $ret;
            $this->response($result, "json", 200);
        } else {
            $result['code'] = 400;
            $result['msg'] = '修改失败';
            $this->response($result, "json", 400);
        }
    }

    public function del()
    {
        $result = [
            'code' => 200,
            'data' => '',
            'msg' => '删除成功'
        ];
        $staff = M("staff");
        $stId = $_POST["stId"];
        $working = M("working");
        $count_w = $working->where("wSTid=$stId")->count();
        if ($count_w > 0) {
            $result['code'] = 400;
            $result['msg'] = '无法删除，请删除该员工的生产记录后再操作';
            $this->response($result, "json", 400);
        }
        $money = M("money");
        $count_m = $money->where("mSTid=$stId")->count();
        if ($count_m > 0) {
            $result['code'] = 400;
            $result['msg'] = '无法删除，请删除该员工的考勤记录后再操作"';
            $this->response($result, "json", 400);
        }
        $ret = $staff->where("stId=$stId")->save(array('deletetime' => time()));
        if ($ret) {
            $result['data'] = $ret;
            $this->response($result, "json", 200);
        } else {
            $result['code'] = 400;
            $result['msg'] = '删除失败';
            $this->response($result, "json", 400);
        }
    }

    //员工列表
    public function lists()
    {
        
        $staff = M("staff");
        $jicgroups = M("jicgroups");
        $product = M("product");
        $gId = $_GET["gId"];
        $where = array();
        if ($gId) {
            $where['stCid'] = $gId;
        }
        if ($_GET['search']) {
            $where['stName'] = array('like', '%' . $_GET['search'] . '%');
        }
        $where['deletetime'] = array('eq', 0);
        $count = $staff->where($where)->count();
        $Page = new \Think\Page($count, 10); // 实例化分页类 传入总记录数和每页显示的记录数(25)
        $rs = $staff->where($where)->order("stId desc")->page($_GET['page'] . ',' . $_GET['limit'])->select();
        if ($rs) {
            foreach ($rs as $k => $val) {
                $info = $jicgroups->where(['gId' => $val['stCid']])->find();
                $rs[$k]['jixz'] = $info['gName'];
                if ($val['gx_cc']) {
                    //工序列表
                    $fds = $product->where('pId in (' . $val['gx_cc'] . ')')->field('pName')->select();
                    if ($fds) {
                        $fwy = '';
                        foreach ($fds as $k1 => $vads) {
                            if ($k1 < 4) {
                                $fwy .= $vads['pName'] . ',';
                            }
                        }
                        $dat = rtrim($fwy, ',');
                        $rs[$k]['sdfae'] = $dat;
                    }
                } else {
                    $rs[$k]['sdfae'] = '---';
                }
            }
        }
        $power = explode(",", $aPowers);
        $result = [
            'code' => 200,
            'data' => [
                'count' => $count,
                'list' => $rs
            ],
            'msg' => '读取成功'
        ];
        $this->ajaxErrReturn($result);
    }


    //查询工序列表
    public function get_gxlist()
    {
        
        $pid = $_GET["pid"];
        $staff = M("product");
        $list = $staff->where(['psId' => $pid])->field('pId,pName')->select();
        if ($list) {
            $html = "<ul style=' 
            height: auto;
            overflow: hidden;padding:0px'>";
            foreach ($list as $k => $val) {
                $html .= "<li style='list-style: none;
               float: left;
               margin: 5px 15px;
               line-height: 25px;'><input type='checkbox' name='sdagt[]' value='" . $val['pId'] . "' /> " . $val['pName'] . "</li>";
            }
            $html .= "</ul>";
        }
        echo $html;
    }


    //添加客户信息
    public function addkh()
    {
        $post = I('post.');
        $user = D("User");
        $admin = M("admin");
        $ut_model = D('Token');
		$token=$post['token'];
        $token_info=$ut_model->where(['token'=>$token])->find();
        $aId = $token_info['aId'];//获取当前登录账号的ID 谁注册就是谁下面的客户
        $u_admin=$admin=$admin->where(['aId'=>$aId])->find();
        $types= $u_admin['atype'];
        $user->startTrans();
        if($types<>1){
            $aId = $post['yw_id'];
        }
        //业务员自己添加客户
        if($this->uinfo['login_type']==1 && $this->uinfo['atype']==1){
            //后台登录 && 业务员
            $aId = $this->uinfo['aId'];
        }
        $username = $post['username'];
        if (empty($username)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '登录账号不能为空！'), 'JSON');
        }
        $user_num = $user->where(['username' => $username])->count();
        if ($user_num > 0) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '该账号已被注册！请重新输入！'), 'JSON');
        }
        $mobile = $post['mobile'];
        if (empty($mobile)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '手机号码不能为空！'), 'JSON');
        }
        $mobile_num = $user->where(['mobile' => $mobile])->count();
        if ($mobile_num > 0) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '该手机号已被注册！请重新输入！'), 'JSON');
        }
        $password = $post['password'];
        if (empty($password)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '密码不能为空！'), 'JSON');
        }
        $names = $post['names'];
        if (empty($names)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '客户姓名不能为空！'), 'JSON');
        }
        $address = $post['address'];
        if (empty($address)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '收货地址不能为空！'), 'JSON');
        }
        $data = [];
        // 客户编号
        $num = $user->where(['types' => 0])->count();
        $data['customer_no'] = $this->getsn('KHBH');;
        $data['username'] = $username;
        $data['mobile'] = $mobile;
        $salt = $this->GetRandStr(6);
        $data['salt'] = $salt;
        $data['password'] = $this->getEncryptPassword($password, $salt);
        $data['names'] = $post['names'];
        $data['address'] = $post['address'];
        $data['sex'] = $post['sex'];
        $data['status'] = 1; 
        $data['addtime'] = date('Y-m-d H:i:s');
        $data['types'] = 0;
        $data['isgl'] = 0;
        $data['issh'] = 1;
        $data['pass_word']= '';
        $data['zhifubao_pay']= '';
        $salt2=$this->GetRandStr(6);
        $aNewPwd="666888";
        $data['salts'] =$salt2;
        $data['pass_word'] =$this->getEncryptPassword($aNewPwd,$salt2);
        if (empty($post['avatar'])) {
            $data['avatar'] = 'https://wages-zymaimai.oss-cn-beijing.aliyuncs.com/2023/03/02/640060c849864.jpg';
        } else {
            $data['avatar'] = $post['avatar'];
        }
        $result = $user->add($data);
        $info['names'] = $data['names'];
        $info['avatar'] = $data['avatar'];
        $info['addtime'] = date("Y-m-d", strtotime($data['addtime']));
        if ($result) {
            $copy_res = $this->mysql_list_copy($result);
            if($copy_res){
                $user->commit();
                $this->ajaxReturn(array('code' => 200, 'msg' => '客户注册成功', 'data' => $info), 'JSON');
            }else{
                $this->ajaxReturn(array('code' => 0, 'msg' => '数据复制失败,请联系管理员'), 'JSON');
            }
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '注册失败'), 'JSON');
        }
    }



    //客户审核列表
    public function waitcheckkh()
    {
        $user = D("User");
        $post = I('post.');
        $where = $this->_search('User');
        $where['types'] = 0;
        $where['issh'] = array('in','0,-1');
        $where['deletetime'] = array('eq', 0);
        // 关键字查找
        // $c = new CommonController;
        if($this->uinfo['login_type']==1 && $this->uinfo['atype']==1){
            //后台登录 && 业务员
            $where['yw_id'] = $this->uinfo['aId'];
        }
        if ($post['keyword']) {
            $where['username|names|mobile'] = array('like', '%' . $post['keyword'] . '%');
        }
        $count = $user->where($where)->count();
        // 分页
        $userlist = $user
            ->where($where)
            //->field('uid,customer_no,username,company,names,mobile,address,sex,status,addtime,issh,tin')
            ->field('*')
            ->page($post['page'])
            ->limit($post['limit'] ? $post['limit'] : 20)
            ->order("uid desc")
            ->select();
        foreach ($userlist as $k => $v) {
            if ($v['sex'] == 0) {
                $userlist[$k]['sex_txt'] = '女';
            }
            if ($v['sex'] == 1) {
                $userlist[$k]['sex_txt'] = '男';
            } else {
                $userlist[$k]['sex_txt'] = '未知';
            }
            if ($v['status'] == 1) {
                $userlist[$k]['status_txt'] = '启用';
            } else {
                $userlist[$k]['status_txt'] = '冻结';
            }
            $userlist[$k]['addtime'] = date("Y-m-d", strtotime($v['addtime']));
        }
        $data['list'] = $userlist;
        $data['count'] = $count;
        if ($userlist) {
            $this->ajaxReturn(array('code' => 200, 'msg' => '查询成功', 'data' => $data), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 200, 'msg' => '查询成功', 'data' => $data), 'JSON');
        }
    }

    // 客户审核通过
    public function khsh()
    {
        $user = M("user");
        $post = I('post.');
        $uid = $post['uid'];
        $uids = (explode(',', $uid));
        $data = [];
        $where['uid'] = ['in', $uids];
        //$data['issh'] = 1;
        //$data['status'] = 1;
        $data['issh'] = I('issh')!==null ? I('issh') : 1;
        $data['status'] = I('status')!==null ? I('status') : 1;
        $data['remark'] = I('remark')?  : '';
        $data['sh_time'] = date("Y-m-d H:i:s");
        $user_info = $user->where($where)->select();
        $result = $user->where($where)->save($data);
        if ($result) {
            $this->ajaxReturn(array('code' => 200, 'msg' => '审核通过成功'), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '审核失败'), 'JSON');
        }
    }

    // 客户审核冻结
    public function shjj()
    {
        $user = M("user");
        $post = I('post.');
        $uid = $post['uid'];
        $remark = $post['remark'];
        $data = ['status' => 0];
        $result = $user->where(['uid' => $uid])->save($data);
        if ($result) {
            $this->ajaxReturn(array('code' => 200, 'msg' => '账号冻结成功'), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '该账号已被冻结'), 'JSON');
        }
    }

    // 客户审核记录删除
    public function delkhsh()
    {
        $user = M("user");
        $post = I('post.');
        $uid = $post['uid'];
        $data['deletetime'] = date("Y-m-d H:i:s");
        $result = $user->where(['uid' => $uid])->save($data);
        if ($result) {
            $this->ajaxReturn(array('code' => 200, 'msg' => '记录删除成功'), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '记录删除失败'), 'JSON');
        }
    }

    //客户列表
    public function userlist()
    {
        $user = D("User");
        $post = I('post.');
        $where['types'] = 0;
        if(I('issh')){
            $where['issh'] = I('issh');
        }
        if(I('status')!=='' && I('status')!==null){
            $where['status'] = I('status');
        }
        if($this->uinfo['login_type']==1 && $this->uinfo['atype']==1){
            //后台登录 && 业务员
            $where['yw_id'] = $this->uinfo['aId'];
        }
        $where['deletetime'] = array('eq', 0);
        // 关键字查找
        if ($post['keyword']) {
            $where['customer_no|username|names|mobile'] = array('like', '%' . $post['keyword'] . '%');
        }
        $uid =$this->kh_uid;
        if($uid) {
            $where['uid'] = $uid;
        }
        $count = $user->where($where)->count();
        $userlist =
            $user
            ->where($where)
            //->field('uid,customer_no,username,company,names,mobile,address,sex,status,addtime,avatar')
            ->field('*')
            ->page($post['page'])
            ->limit($post['limit'] ? $post['limit'] : 20)
            ->order("uid desc")
            ->select();
        foreach ($userlist as $k => $v) {
            if ($v['sex'] == 0) {
                $userlist[$k]['sex_txt'] = '女';
            }
            if ($v['sex'] == 1) {
                $userlist[$k]['sex_txt'] = '男';
            }
            if ($v['status'] == 1) {
                $userlist[$k]['status_txt'] = '启用';
            } else {
                $userlist[$k]['status_txt'] = '冻结';
            }
            unset($userlist[$k]['password']);
            $userlist[$k]['addtime'] = date("Y-m-d", strtotime($v['addtime']));
        }
        $data['list'] = $userlist;
        $data['count'] = $count;
        if ($userlist) {
            $this->ajaxReturn(array('code' => 200, 'msg' => '查询成功', 'data' => $data), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 200, 'msg' => '查询成功', 'data' => $data), 'JSON');
        }
    }

    // 单条客户信息
    public function userinfo()
    {
        $user = M("user");
        $admin = M("admin");
        $caiwu = M("caiwu");
        $post = I('post.');
        $where['types'] = 0;
        $where['deletetime'] = array('eq', 0);
        $where['uid'] = $post['uid'];
        $userinfo = $user->where($where)->field('uid,customer_no,amount,username,company,names,mobile,address,sex,status,addtime,avatar,credit,yw_id,customer_attr')->find();
        if ($userinfo) {
            //业务员
            if($userinfo['yw_id']){
                $userinfo['yw_name']= $admin->where(['aId'=>$userinfo['yw_id']])->getField('aName');
            }else{
                $userinfo['yw_name']='-没有对接业务员-';
            }
            if($userinfo['customer_attr']==1){
                $userinfo['shuxign']='充值客户';
            }
            else if($userinfo['customer_attr']==2){
                $userinfo['shuxign']='月结客户';
            }
            else if($userinfo['customer_attr']==3){
                $userinfo['shuxign']='现金客户';
            }
            else if($userinfo['customer_attr']==4){
                $userinfo['shuxign']='欠款客户';
            }else{
                $userinfo['shuxign']='-';
            }
            $total=$caiwu->where(['uid'=>$post['uid']])->sum('total');
            $pay_amount=$caiwu->where(['uid'=>$post['uid']])->sum('pay_amount');
            $danqian_qiankuan=$total-$pay_amount;
            $userinfo['danqian_qiankuan']=$danqian_qiankuan;//查询该客户所有欠款
            $this->ajaxReturn(array('code' => 200, 'msg' => '查询成功', 'data' => $userinfo), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '当前客户不存在', 'data' => $userinfo), 'JSON');
        }
    }


    // 更新客户信息
    public function updatekh()
    {
        $user = M("user");
        $post = I('post.');
        $data = $post;
        $data['types'] = 0;
        $uid = $data['uid'];
        if (empty($uid)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '用户ID不能为空！'), 'JSON');
        }
        $userinfo = $user->where(['uid' => $uid])->find();
        if (empty($userinfo)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '该用户不存在'), 'JSON');
        }
        $password = $data['password'];
        if ($password != $userinfo['password']) {
            $salt = $this->GetRandStr(6);
            $data['salt'] = $salt;
            $data['password'] = $this->getEncryptPassword($data['password'], $salt);
        } else {
            unset($data['password']);
        }
        $mobile = $data['mobile'];
        if (empty($mobile)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '手机号码不能为空！'), 'JSON');
        } else {
            if ($mobile != $userinfo['mobile']) {
                $mobile_num = $user->where(['mobile' => $mobile])->count();
                if ($mobile_num > 0) {
                    $this->ajaxReturn(array('code' => 0, 'msg' => '该手机号已被注册！请重新输入！'), 'JSON');
                }
            } else {
                unset($data['mobile']);
            }
        }

        $names = $data['names'];
        if (empty($names)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '客户姓名不能为空！'), 'JSON');
        }
        $address = $data['address'];
        if (empty($address)) {
            $this->ajaxReturn(array('code' => 0, 'msg' => '收货地址不能为空！'), 'JSON');
        }
        // 用户上传的头像
        if (empty($data['avatar'])) {
            $data['avatar'] = $userinfo['avatar'];
        } else {
            $data['avatar'] = $post['avatar'];
        }
        $data['address'] = $post['address'];
        $data['sex'] = $post['sex'];
        $data['status'] = $post['status'];
        unset($data['token']);
        $ret = $user->where("uid=$uid")->save($data);
        $user_info = $user->where(['uid' => $uid])->field('uid,customer_no,username,names,mobile,address,sex,status,addtime,avatar')->find();
        if ($user_info['sex'] == 0) {
            $user_info['sex_txt'] = '女';
        }
        if ($user_info['sex'] == 1) {
            $user_info['sex_txt'] = '男';
        }
        if ($user_info['status'] == 1) {
            $user_info['status_txt'] = '启用';
        } else {
            $user_info['status_txt'] = '冻结';
        }
        $user_info['addtime'] = date("Y-m-d", strtotime($user_info['addtime']));
        if ($ret) {
            $this->ajaxReturn(array('code' => 200, 'msg' => '更新成功', 'data' => $user_info), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '更新失败'), 'JSON');
        }
    }

    // 删除客户
    public function delkh()
    {
        $user = M("user");
        $post = I('post.');
        $uid = $post["uid"];
        $user = M("user");
        $ret = $user->where("uid=$uid")->save(array('deletetime' => date('Y-m-d H:i:s'),'mobile'=>''));
        if ($ret) {
            $this->ajaxReturn(array('code' => 200, 'msg' => '删除成功'), 'JSON');
        } else {
            $this->ajaxReturn(array('code' => 0, 'msg' => '删除失败'), 'JSON');
        }
    }

    // 客户账单列表
    public function customer_bill()
    {
        $post = I('post.');
        $caiwu = D("caiwu");
        $user = M("user");
        $caiwu_detail=M("caiwu_detail");
        $order = M("production_order");
        $where = [];
        $order_status = $post['order_status'];
        $uids = $post['uid'];
        $page=$post['page']?$post['page']:1;
        $limit=$post['limit']?$post['limit']:20;
        $uid =$this->kh_uid;
        if($uid) {
            $where['caiwu.uid'] = $uid;
        }
        if($uids) {
            $where['caiwu.uid'] = $uids;
        }
        if($post['keyword']) {
            $where['os.customer_no|os.customer_name|os.ordersn|os.order_sn|os.goods_name'] = array('like', '%' . $post['keyword'] . '%');
        }
        if ($order_status<>'-1') {
            $where['caiwu.status'] = $order_status;
        }
        $status = $post['status'];
        if ($status<>'-1') {
            $where['os.status'] = $status;
        }
        if($this->uinfo['login_type']==1 && $this->uinfo['atype']==1){
            $where['os.yw_id'] = $this->uinfo['aId'];
        }
        $count = $caiwu->alias('caiwu')->join('fa_renshi_production_order as os ON os.id = caiwu.order_id','LEFT')->where($where)->count();
        $caiwu_list =$caiwu->alias('caiwu')->join('fa_renshi_production_order as os ON os.id = caiwu.order_id','LEFT') 
            ->where($where)
            ->page($page, $limit)
            ->order("caiwu.id desc")
            ->field('caiwu.goods_name,caiwu.order_id,caiwu.sc_goods_number,caiwu.total,caiwu.pay_amount,caiwu.status,os.ordersn,os.uid,os.customer_name,os.owner,os.status as stuc')
            ->select();
        foreach ($caiwu_list as $k => $val) {
            $user_info = $user->where(['uid' => $val['uid']])->find();
            //查询客户信息
            $order_info = $order->where(['id' => $val['order_id']])->where($where2)->find();
            if (!$order_info) {
                $caiwu_list = [];
                $count = 0;
            } else {
                $caiwu_list[$k]['names'] = $user_info['names'];
                if(empty($val['customer_name'])){
                    $caiwu_list[$k]['customer_name'] = $user_info['names'];
                }
                //待支付金额
                $caiwu_list[$k]['wait_payment_amount'] = $val['total']-$val['pay_amount'];
                $now_zhiftime = $caiwu_detail->where(['order_id' => $val['order_id'],'is_delete'=>0])->order('id desc')->getField('add_time');
                if($now_zhiftime){
                    $caiwu_list[$k]['near_zhiftime'] = date('Y-m-d',$now_zhiftime);//最近支付日期
                }else{
                    $caiwu_list[$k]['near_zhiftime'] ='等待支付';
                }
               
                $caiwu_list[$k]['price']="￥".round($val['total']/$val['sc_goods_number'],2);
                if ($val['payment'] == 'wxpay') {
                    $caiwu_list[$k]['dj_zffs'] = '微信';
                } elseif ($val['payment'] == 'alipay') {
                    $caiwu_list[$k]['dj_zffs'] = '支付宝';
                } elseif ($val['payment'] == 'cash') {
                    $caiwu_list[$k]['dj_zffs'] = '现金';
                }

                // 尾款支付方式
                if ($val['wk_payment'] == 'wxpay') {
                    $caiwu_list[$k]['wk_zffs'] = '微信';
                } elseif ($val['wk_payment'] == 'alipay') {
                    $caiwu_list[$k]['wk_zffs'] = '支付宝';
                } elseif ($val['wk_payment'] == 'cash') {
                    $caiwu_list[$k]['wk_zffs'] = '现金';
                }

                // 付款状态
                if ($val['status'] == '0') {
                    $caiwu_list[$k]['fk_status'] = '未付款';
                } elseif ($val['status'] == '1') {
                    $caiwu_list[$k]['fk_status'] = '已付款';
                } elseif ($val['status'] == '2') {
                    $caiwu_list[$k]['fk_status'] = '等待支付';
                } elseif ($val['status'] == '3') {
                    $caiwu_list[$k]['fk_status'] = '完成';
                }

                // 订单状态
                if ($caiwu_list[$k]['stuc'] == '0') {
                    $caiwu_list[$k]['order_zt'] = '常规';
                } elseif ($caiwu_list[$k]['stuc'] == '1') {
                    $caiwu_list[$k]['order_zt'] = '加急';
                } elseif ($caiwu_list[$k]['stuc'] == '2') {
                    $caiwu_list[$k]['order_zt'] = '暂停';
                } elseif ($caiwu_list[$k]['stuc'] == '3') {
                    $caiwu_list[$k]['order_zt'] = '等待通知';
                } 
            }
    

        }
        $data_cc['code'] = 200;
        $data_cc['msg'] = "查询成功";
        $data_cc['data']['count']=$count;
        $data_cc['data']['list']=$caiwu_list;
        exit(json_encode($data_cc));
    }

    // 客户账单 
    public function customer_detail(){
        $detail = I('post.');
        $caiwu = M("caiwu");
        $user = M("user");
        $order_model = M("production_order");
        $order_id = $detail['order_id'];
        $info=$caiwu->where(['order_id'=>$order_id])->find();
        if($info){
            $ordersn=$order_model->where(['id'=>$order_id])->getField('ordersn');
            $user_info=$user->where(['uid'=>$info['uid']])->field('uid,customer_no,names')->find();
            $user_info['danqian_qiankuan']=$info['total']-$info['pay_amount'];
            $user_info['total']=$info['total'];
            $user_info['pay_amount']=$info['pay_amount'];
            $user_info['ordersn']=$ordersn;
            $data_cc['code'] = 200;
            $data_cc['msg'] = "查询成功";
            $data_cc['data']['info']=$user_info;
            exit(json_encode($data_cc));
        }else{
            $data_cc['code'] = 0;
            $data_cc['msg'] = "信息查询失败";
            exit(json_encode($data_cc));
        }
      
    }
    //支付流水列表
    public function customer_paymenlist(){
        $detail = I('post.');
        $caiwu_model = M("caiwu_customer_order");
        $order_id = $detail['order_id'];
        $page=$detail['page']?$detail['page']:1;
        $limit=$detail['limit']?$detail['limit']:20;
        $where['order_id']=$order_id;
        $where['isdel']=0;
        $count = $caiwu_model->where($where)->count();
        $list =$caiwu_model->where($where)->page($page, $limit)->order("id desc")->select();
        if($list){
            foreach ($list as $k => $val) {
                if ($val['pay_type'] == 1) {
                    $list[$k]['payment_type'] = '银行转账';
                } elseif ($val['pay_type'] == 2) {
                    $list[$k]['payment_type'] = '微信支付';
                } elseif ($val['pay_type'] == 3) {
                    $list[$k]['payment_type'] = '支付宝';
                }
                elseif ($val['pay_type'] == 4) {
                    $list[$k]['payment_type'] = '线下支付';
                }
                elseif ($val['type'] == 5) {
                    $list[$k]['payment_type'] = '余额支付';
                }
                elseif ($val['type'] ==10) {
                    $list[$k]['payment_type'] = '其他支付方式';
                } 
                $list[$k]['zhifu_time'] = date('Y-m-d',$val['add_time']);
            } 
        }
              
        $data_cc['code'] = 200;
        $data_cc['msg'] = "查询成功";
        $data_cc['data']['count']=$count;
        $data_cc['data']['list']=$list;
        exit(json_encode($data_cc));
    }
    
    public function detail_pay(){
        $detail = I('post.');
        $caiwu_detail = M("caiwu_customer_order");
        $id = $detail['id'];
        $info=$caiwu_detail->where(['id'=>$id,'isdel'=>0])->find();
        if($info){
            $data_cc['code'] = 200;
            $data_cc['msg'] = "查询成功";
            $data_cc['data']['info']=$info;
            exit(json_encode($data_cc));
        }else{
            $data_cc['code'] = 0;
            $data_cc['msg'] = "信息查询失败";
            exit(json_encode($data_cc));
        }
    }
   //添加付款信息
   public function add_pay(){
        $detail = I('post.');
        $caiwu_detail = M("caiwu_customer_order");
        $caiwu = M("caiwu");
        $user = M("user");
        $order_model = M("production_order");
        $order_id = $detail['order_id'];
        $amount = $detail['amount'];
        $pay_type = $detail['pay_type'];
        $pz_pic = $detail['pz_pic'];
        $remark=$detail['remark'];
        if(empty($order_id)){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "订单ID必传";
            exit(json_encode($data_cc));
        }
        if(empty($amount)){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "请输入支付金额";
            exit(json_encode($data_cc));
        }
        if(empty($pay_type)){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "请选择支付方式";
            exit(json_encode($data_cc));
        }
   
 
        $datac1=[];
        $datac1['order_id']=$order_id;
        $datac1['cw_id']=$caiwu->where(['order_id'=>$order_id])->getField('id');
        $cda_ct=$order_model->where(['id'=>$order_id])->field('yw_id,uid,ordersn,order_sn')->find();
        $datac1['amount']=$amount;
        $uid=$cda_ct['uid'];
        if($uid){
            $customer_attr=$user->where(['uid'=>$uid])->getField('customer_attr');
            if($customer_attr<>1 && $pay_type==5){
                $data_cc['code'] = 0;
                $data_cc['msg'] = "该客户不是充值客户,无法使用余额支付功能";
                exit(json_encode($data_cc));
            }
        }
        $datac1['uid']=$cda_ct['uid'];
        $datac1['yw_id']=$cda_ct['yw_id'];
        $datac1['ordersn']=$cda_ct['ordersn'];
        $datac1['order_sn']=$cda_ct['order_sn'];
        $datac1['pay_type']=$pay_type;
        $datac1['pz_pic']=$pz_pic;
        $datac1['remark']=$remark;
        $datac1['add_time']=time();
        $result=$caiwu_detail->add($datac1);
        if($result){
            $data_cc['code'] = 200;
            $data_cc['msg'] = "提交成功,等待业务员审核。";
            exit(json_encode($data_cc));
        }else{
            $data_cc['code'] = 0;
            $data_cc['msg'] = "提交失败";
            exit(json_encode($data_cc));
        }
   }
   public function edit_pay(){
    $detail = I('post.');
    $caiwu_detail = M("caiwu_customer_order");
    $caiwu = M("caiwu");
    $user = M("user");
    $order_model = M("production_order");
    $order_id = $detail['order_id'];
    $amount = $detail['amount'];
    $pay_type = $detail['pay_type'];
    $pz_pic = $detail['pz_pic'];
    $remark=$detail['remark'];
    $id=$detail['id'];
    $infoc=$caiwu_detail->where(['id'=>$id])->find();
    if(empty($id)){
        $data_cc['code'] = 0;
        $data_cc['msg'] = "ID必传";
        exit(json_encode($data_cc));
    }
    if(empty($order_id)){
        $data_cc['code'] = 0;
        $data_cc['msg'] = "订单ID必传";
        exit(json_encode($data_cc));
    }
    if(empty($amount)){
        $data_cc['code'] = 0;
        $data_cc['msg'] = "请输入支付金额";
        exit(json_encode($data_cc));
    }
    if(empty($pay_type)){
        $data_cc['code'] = 0;
        $data_cc['msg'] = "请选择支付方式";
        exit(json_encode($data_cc));
    }
    $uid=$infoc['uid'];
    if($uid){
        $customer_attr=$user->where(['uid'=>$uid])->getField('customer_attr');
        if($customer_attr<>1 && $pay_type==5){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "该客户不是充值客户,无法使用余额支付功能";
            exit(json_encode($data_cc));
        }
    }

    $datac1=[];
    $datac1['amount']=$amount;
    $datac1['pay_type']=$pay_type;
    $datac1['pz_pic']=$pz_pic;
    $datac1['remark']=$remark;
    $datac1['status_f']=0;
    $datac1['reason']='';
    $datac1['yw_shtime']='';
    $result=$caiwu_detail->where(['id'=>$id])->save($datac1);
        if($result){
            $data_cc['code'] = 200;
            $data_cc['msg'] = "编辑成功,等待业务员审核。";
            exit(json_encode($data_cc));
        }else{
            $data_cc['code'] = 0;
            $data_cc['msg'] = "编辑失败";
            exit(json_encode($data_cc));
        }
   }
   
    public function sh_pay(){
        $detail = I('post.');
        $id=$detail['id'];
        $caiwu_detail = M("caiwu_customer_order");
        $user = M("user");
        $uid=$this->kh_uid;
        $info=$caiwu_detail->where(['id'=>$id])->find();
        $uids=$info['uid'];
        $pay_type=$info['pay_type'];
        if($uids){
            $customer_attr=$user->where(['uid'=>$uid])->getField('customer_attr');
            if($customer_attr<>1 && $pay_type==5){
                $data_cc['code'] = 0;
                $data_cc['msg'] = "该客户不是充值客户使用了余额支付功能,无法审核。";
                exit(json_encode($data_cc));
            }
        }
        if($uid==$uids){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "不能审核自己的财务账单";
            exit(json_encode($data_cc));
        }else{
               $result=$caiwu_detail->where(['id'=>$id])->save(['sh_time'=>time(),'status_c'=>1]);
            if($result){
                $data_cc['code'] = 200;
                $data_cc['msg'] = "审核成功,等待财务审核.";
                exit(json_encode($data_cc));
            }else{
                $data_cc['code'] = 0;
                $data_cc['msg'] = "审核失败";
                exit(json_encode($data_cc));
            }
        }
        
    }

   
    //删除付款信息
    public function del_pay(){
        $detail = I('post.');
        $id=$detail['id'];
        $caiwu_detail = M("caiwu_customer_order");
        $mincf=$caiwu_detail->where(['id'=>$id])->find();
        if($mincf['status_c']==1){
            $data_cc['code'] = 0;
            $data_cc['msg'] = "已审核通过了,无法删除。";
            exit(json_encode($data_cc));
        } 
        $result=$caiwu_detail->where(['id'=>$id])->save(['isdel'=>time(),'status_c'=>0]);
        if($result){
            $data_cc['code'] = 200;
            $data_cc['msg'] = "删除成功";
            exit(json_encode($data_cc));
        }else{
            $data_cc['code'] = 0;
            $data_cc['msg'] = "审核失败";
            exit(json_encode($data_cc));
        }
    }
    


    // 密码验证参数
    function GetRandStr($length)
    {
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str); //打乱字符串
        $rands = substr($randStr, 0, $length); //substr(string,start,length);返回字符串的一部分
        return $rands;
    }

    // 密码加密
    function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    // 头像图片处理
    public function getPicAttr($value)
    {
        $pic_url = '';
        if ($value) {
            $preg = "/^http(s)?:\\/\\/.+/";
            if (preg_match($preg, $value)) {
                $pic_url =  $value; //完整url
            } else {
                $pic_url =  C('Wimgurl') . '/' . $value;
            }
        }
        return $pic_url;
    }

    //标准数据库数据复制
    function mysql_list_copy($uid){
        $default_upper_model = M('user_mysql_default_list');//默认上装数据库
        $default_below_model = M('user_mysql_default_listc');//默认下装数据库
        $copy_upper_model =  M('user_mysql_list');//复制上装数据库
        $copy_below_model =  M('user_mysql_listc');//复制下装数据库
        $d_upper_list = $default_upper_model->where(['isdel'=>0])->select();
        $d_below_list = $default_below_model->where(['isdel'=>0])->select();
        
        $copy_upper_data = [];
        foreach($d_upper_list as $k=>$v){
            $up_data = $v;
            unset($up_data['id']);
            $up_data['uid'] = $uid;
            $copy_upper_data[] = $up_data;
            $copy_upper_model->add($up_data);
        }
        $copy_below_data = [];
        foreach($d_below_list as $bk=>$bv){
            $below_data = $bv;
            unset($below_data['id']);
            $below_data['uid'] = $uid;
            $copy_below_data[] = $below_data;
            $below_res = $copy_below_model->add($below_data);
        }
        return true;
        // if( $below_res){
          
        // }else{
        //     return false;
        // }
    }
}
